import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Calendar;
import java.util.TimerTask;

import main.CEPLFunctions;

public class ByteArrayPusher extends TimerTask {
	private ArrayDeque<byte[]> arrays = null;
	private boolean active = false;

	public ByteArrayPusher() {
		arrays = new ArrayDeque<byte[]>();
	}

	public void clear() {
		if (arrays != null)
			arrays.clear();

		active = false;
	}

	public synchronized void addByteArray(byte[] arr) {
		Calendar calendar = Calendar.getInstance();
		java.util.Date now = calendar.getTime();
		java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(
				now.getTime());
		long ts = currentTimestamp.getTime();

		ByteBuffer push = ByteBuffer.allocate(arr.length + 8);
		ByteBuffer ori = ByteBuffer.wrap(arr);
		push.put(ori);
		push.putLong(ts);

		arrays.add(push.array());
	}

	private synchronized byte[] getOldestByteArray() {
		return arrays.pop();
	}

	private synchronized long getNbArrays() {
		return arrays.size();
	}

	@Override
	public void run() {
		if (active)
			return;
		active = true;
		while (getNbArrays() != 0) {
			byte[] arr = getOldestByteArray();

			ByteBuffer buf = ByteBuffer.wrap(arr);
			long streamID = buf.getLong();
			byte[] arrToPush = new byte[buf.remaining()];
			buf.get(arrToPush);

			CEPLFunctions.Events.pushEvent(streamID, arrToPush);
		}
		active = false;
	}
}
